package com.young.mybatis;

import com.young.entity.Pet;
import org.apache.commons.dbcp.BasicDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;

/**
 * 描述:
 *
 * @author BluceYoung
 * @create 2020-07-01 10:15
 * B站：TeacherYoung凌风
 * www.teacheryoung.com
 */
public class V1 {

    public <T> List<T> getList(String statementId, Object par){
        List<T> list=new ArrayList<T>();

        //2.读取properties文件
        Properties properties=getProperties("database.properties");
        //1.用BasicDataSource管理连接，省去创建连接和关闭资源的代码
        BasicDataSource dataSource=getDataSource(properties);

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        try {
            connection = dataSource.getConnection();


            preparedStatement = connection.prepareStatement(properties.getProperty("db.sql."+statementId));

            if(par instanceof Map){//多参数
                Map map=(Map)par;
                String cols = properties.getProperty("db.sql." + statementId + ".cols");
                String[] colNames=cols.split(",");
                for (int i = 0; i < colNames.length; i++) {
                    String key=colNames[i];//参数名
                    Object value=map.get(key);//参数值
                    preparedStatement.setObject(i+1,value);
                }
            }else{//单参数
                preparedStatement.setObject(1, par);
            }

            rs = preparedStatement.executeQuery();

            //获取返回值类型
            String className=properties.getProperty("db.sql." + statementId + ".resultclass");
            Class clazz=Class.forName(className);

            while (rs.next()) {
                Object result = clazz.newInstance();
                ResultSetMetaData metaData = rs.getMetaData();//获取查询结果集的列
                for (int i = 1; i <= metaData.getColumnCount(); i++) {//遍历结果集的所有列，下标从1开始
                    String colName = metaData.getColumnName(i);//这个列名就是类属性的名字
                    try {
                        Field field=clazz.getDeclaredField(colName);
                        field.setAccessible(true);
                        field.set(result,rs.getObject(i));//强制为对象的属性赋值
                    } catch (Exception e) {
                        //e.printStackTrace();
                    }
                }
                list.add((T)result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private Properties getProperties(String path){
        Properties properties=new Properties();
        InputStream inputStream=this.getClass().getClassLoader().getResourceAsStream("database.properties");
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

    private BasicDataSource getDataSource(Properties properties){
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(properties.getProperty("db.driver"));
        dataSource.setUrl(properties.getProperty("db.url"));
        dataSource.setUsername(properties.getProperty("db.user"));
        dataSource.setPassword(properties.getProperty("db.password"));
        return dataSource;
    }

}
